package client.server.imp;


import client.common.exception.ServerException;
import client.common.pojo.EncryptPNumber;
import client.common.util.EncryptUtil;
import client.common.util.JWTUtilS;
import client.common.util.RedisUtil;
import client.common.util.RegexUtil;
import client.controller.param.LoginParam;
import client.controller.param.LoginRequestParamByEmail;
import client.controller.param.LoginRequestParamByUP;
import client.controller.param.UserRequestParam;
import client.dao.dataObject.UserDO;
import client.dao.mapper.UserMapper;
import client.server.UserServer;
import client.server.exceptionCode.ServerConstantCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static client.common.constant.Constants.LOGIN_EMAIL_PREFIX;

@Slf4j
@Service
public class UserServerImp implements UserServer {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public Boolean register(UserRequestParam user) {
        if (user.getIdentity().equals("ADMIN") || user.getIdentity().equals("NORMAL")) {
            return registerAct(user);
        } else {
            throw new ServerException(ServerConstantCode.IDENTITY_FORMAT_ERROR.getCode(), ServerConstantCode.IDENTITY_FORMAT_ERROR.getMessage() + " identiy: " + user.getIdentity());
        }
    }

    private boolean registerAct(UserRequestParam user) {
        //验证格式的正确
        checkUserFormat(user);

        UserDO userDO = new UserDO(user.getName(), EncryptUtil.encryptHash(user.getPassword()), user.getMail(),
                new EncryptPNumber(user.getPhoneNumber()), user.getIdentity());

        userMapper.register(userDO);

        log.info("注册成功: {}", userDO);

        return true;
    }


    private void checkUserFormat(UserRequestParam user) {

        if (!RegexUtil.checkMail(user.getMail())) {
            throw new ServerException(ServerConstantCode.EMAIL_FORMAT_ERROR);
        }

        if (userMapper.getUserByEmail(user.getMail()) != null) {
            throw new ServerException(ServerConstantCode.EMAIL_EXIST_ERROR);
        }

        if (!RegexUtil.checkMobile(user.getPhoneNumber())) {
            throw new ServerException(ServerConstantCode.PHONE_FORMAT_ERROR);
        }

        if (userMapper.getUserByPhoneNumber(new EncryptPNumber(user.getPhoneNumber())) != null) {
            throw new ServerException(ServerConstantCode.PHONE_EXIST_ERROR);
        }

        if(user.getIdentity().equals("ADMIN") && !RegexUtil.checkPassword(user.getPassword())) {
            throw new ServerException(ServerConstantCode.PASSWORD_FORMAT_ERROR);
        }

        if(user.getName().contains(" ")){
            throw new ServerException(ServerConstantCode.USERNAME_CONTAINS_SPACE);
        }

    }

    public String login(LoginParam param) {
        if (param instanceof LoginRequestParamByUP loginRequestParamByUP) {
            //使用密码登录
            return loginUP(loginRequestParamByUP);
        } else if (param instanceof LoginRequestParamByEmail loginRequestParamByEmail) {
            //使用邮箱登录
            return loginEmail(loginRequestParamByEmail);
        } else {
            throw new ServerException(ServerConstantCode.LOGIN_ERROR);
        }
    }

    private String loginEmail(LoginRequestParamByEmail loginRequestParamByEmail) {

        if (!verifyEmail(loginRequestParamByEmail)) {
            log.info("邮箱输入错误,没有该邮箱");
            throw new ServerException(ServerConstantCode.EMAIL_ERROR);
        }

        //验证验证码是不是对的
        String s = redisUtil.get(LOGIN_EMAIL_PREFIX + loginRequestParamByEmail.getEmail());
        if (s == null) {
            log.info("邮箱输入错误,没有验证码");
            throw new ServerException(ServerConstantCode.EMAIL_ERROR);
        }

        if (!loginRequestParamByEmail.getVerificationCode().equals(s)) {
            log.info("验证码校验错误 {}", loginRequestParamByEmail.getVerificationCode());
            throw new ServerException(ServerConstantCode.EMAIL_VERIFY_ERROR);
        }

        //验证成功
        String token = JWTUtilS.getToken(loginRequestParamByEmail);

        log.info("验证码校验成功，获取到email token {}", token);

        return token;
    }

    private boolean verifyEmail(LoginRequestParamByEmail paramByEmail) {
        UserDO u = userMapper.getUserByEmail(paramByEmail.getEmail());

        if (u == null) {
            log.error("输入的邮箱不存在");
            return false;
        }
        return true;
    }

    private String loginUP(LoginRequestParamByUP user) {
        if (!RegexUtil.checkPassword(user.getPassword())) {
            throw new ServerException(ServerConstantCode.PASSWORD_FORMAT_ERROR);
        }

        UserDO info = userMapper.getUserByUsernameAndPassword(user.getLoginName(), EncryptUtil.encryptHash(user.getPassword()));

        if(info == null) {
            throw new ServerException(ServerConstantCode.UP_INCORRECT);
        }

        info.setPassword("");

        return JWTUtilS.getToken(info);
    }
}
